package com.ljx.funchat.common.event.listener;

import com.ljx.funchat.chat.domain.entity.Redbag;
import com.ljx.funchat.chat.service.ChatService;
import com.ljx.funchat.chat.service.adapter.RedbagAdapter;
import com.ljx.funchat.common.constant.RedisKey;
import com.ljx.funchat.common.event.RedbagSendEvent;
import com.ljx.funchat.common.event.UserApplyEvent;
import com.ljx.funchat.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


/**
 * 发送红包监听器
 */
@Slf4j
@Component
public class RedbagSendListener {

    @Autowired
    private ChatService chatService;

    /**
     * 发红包消息
     * @param event
     */
    @Async
    @EventListener(classes = RedbagSendEvent.class)
    public void sendMsg(RedbagSendEvent event) {
        Redbag redbag = event.getRedbag();
        Long uid = event.getUid();
        chatService.sendMsg(uid, RedbagAdapter.buildRedbagSendReq(redbag));
    }

    @Async
    @EventListener(classes = RedbagSendEvent.class)
    public void saveRedis(RedbagSendEvent event) {
        Redbag redbag = event.getRedbag();
        // 红包过期事件
        RedisUtils.set(RedisKey.getKey(RedisKey.REDBAG_VALID, redbag.getId()), "1", RedisKey.REDBAG_VALID_EXPIRE, TimeUnit.HOURS);
    }

}
